/**
 * 浏览器书签工具函数
 */
import { MD5 } from '@/utils/md5';
import { storage } from '@/utils/storage';
import { CATEGORIES_STORE, URLS_STORE } from '@/enum';
// 验证并清理书签数据
function validateBookmarkData(bookmark) {
  try {
    // 基本数据验证
    if (!bookmark || typeof bookmark !== 'object') {
      console.warn('Invalid bookmark data, not an object');
      return null;
    }
    // 确保title字段存在
    if (!bookmark.title || typeof bookmark.title !== 'string') {
      console.warn('Invalid bookmark title:', bookmark.title);
      bookmark.title = '未命名书签';
    }

    // 确保url字段是有效的URL格式（对于书签项）
    if (bookmark.url !== undefined) {
      if (typeof bookmark.url !== 'string' || !bookmark.url.startsWith('http')) {
        console.warn('Invalid bookmark URL:', bookmark.url);
        // 设为空字符串而不是null，避免类型错误
        bookmark.url = '';
      }
    }

    return bookmark;
  } catch (e) {
    console.error('Error validating bookmark data:', e);
    return null;
  }
}

/**
 * 递归处理书签树，提取分类和URL
 * @param {Array} nodes - 书签节点数组
 * @param {Object} result - 结果对象，包含分类和URL
 * @param {Number} parentId - 父分类ID
 * @param {Number} categoryIdCounter - 分类ID计数器
 * @param {Number} urlIdCounter - URL ID计数器
 * @returns {Object} 更新后的结果对象
 */
function processBookmarkNodes(nodes, result, parentId = 0, categoryIdCounter = 0, urlIdCounter = 0) {
  for (const node of nodes) {
    try {
      if (node.children) {
        // 这是一个文件夹/分类
        categoryIdCounter++;
        const categoryId = categoryIdCounter;

        // 添加分类
        const category = validateBookmarkData({
          id: categoryId,
          name: node.title || '未命名文件夹',
          parentId: parentId
        });

        if (category) {
          result.categories.push(category);
        }

        // 递归处理子节点
        const counters = processBookmarkNodes(
          node.children,
          result,
          categoryId,
          categoryIdCounter,
          urlIdCounter
        );

        categoryIdCounter = counters.categoryIdCounter;
        urlIdCounter = counters.urlIdCounter;
      } else {
        // 这是一个书签
        urlIdCounter++;

        // 添加URL，并进行数据验证
        const url = validateBookmarkData({
          id: urlIdCounter,
          title: node.title || '未命名书签',
          url: node.url || '',
          categoryId: parentId || 1, // 如果没有parentId，默认放在ID为1的分类中
          dateAdded: node.dateAdded || new Date().getTime()
        });

        if (url && url.url) {  // 只添加有效的URL
          result.urls.push(url);
        }
      }
    } catch (e) {
      console.error('Error processing bookmark node:', e, node);
      // 继续处理其他节点
    }
  }
  return {
    categoryIdCounter,
    urlIdCounter
  };
}

/**
 * 获取所有Chrome书签
 * @returns {Promise<Object>} 包含所有分类和书签的对象
 */
export const getAllChromeBookmarks = () => {
  return new Promise((resolve, reject) => {
    // 检查是否在Chrome扩展环境中
    if (typeof chrome === 'undefined' || !chrome.bookmarks) {
      reject(new Error('非Chrome扩展环境，无法访问书签API'));
      return;
    }
    chrome.bookmarks.getTree((bookmarkTreeNodes) => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }
      const result = {
        categories: [
          // 默认添加"根"分类
          { id: MD5('默认分类'), name: '默认分类', parentId: 0 }
        ],
        urls: []
      };

      // 处理书签树
      processBookmarkNodes(bookmarkTreeNodes, result);

      resolve(result);
    });
  });
};

/**
 * 导入Chrome书签到存储中
 * @param {Boolean} merge - 是否合并现有数据，默认为false（覆盖）
 * @returns {Promise<Object>} 导入结果
 */
export const importChromeBookmarks = async (merge = false) => {
  try {
    console.log('Starting Chrome bookmarks import, merge mode:', merge);
    const chromeBookmarks = await getAllChromeBookmarks();
    console.log('Retrieved Chrome bookmarks:', chromeBookmarks);

    const oldCategories = chromeBookmarks.categories;
    // 处理导入数据的分类
    const categories = chromeBookmarks.categories.map(c => {
      return {
        id: MD5(c.name),
        name: c.name,
        parentId: c.parentId
      };
    });
    chromeBookmarks.categories = categories;
    // 处理导入数据的URL
    const urls = chromeBookmarks.urls.map(u => {
      // 获取导入数据的分类ID
      const categoryName = oldCategories.find(c => c.id === u.categoryId)?.name ?? "默认分类";
      return {
        id: MD5(u.url),
        title: u.title,
        url: u.url,
        categoryId: MD5(categoryName),
        dateAdded: u.dateAdded
      };
    });
    chromeBookmarks.urls = urls;


    // 确保数据有效
    if (!chromeBookmarks || !chromeBookmarks.categories || !chromeBookmarks.urls) {
      throw new Error('无效的书签数据');
    }

    if (merge) {
      // 合并模式：获取现有数据，然后合并
      return new Promise((resolve, reject) => {
        storage.get([CATEGORIES_STORE, URLS_STORE], async (result) => {
          try {
            console.log('Existing data for merge:', result);
            const existingCategories = result[CATEGORIES_STORE] || [];
            const existingUrls = result[URLS_STORE] || [];

            // 找出最大ID
            const maxCategoryId = existingCategories.length > 0
              ? Math.max(...existingCategories.map(c => c.id))
              : 0;
            const maxUrlId = existingUrls.length > 0
              ? Math.max(...existingUrls.map(u => u.id))
              : 0;

            console.log('Max existing IDs - categories:', maxCategoryId, 'URLs:', maxUrlId);

            // 调整新数据的ID以避免冲突
            chromeBookmarks.categories.forEach(c => {
              if (c.id !== 1) { // 保留默认分类的ID
                c.id += maxCategoryId;
              }
              if (c.parentId > 1) {
                c.parentId += maxCategoryId;
              }
            });

            chromeBookmarks.urls.forEach(u => {
              u.id += maxUrlId;
              if (u.categoryId > 1) {
                u.categoryId += maxCategoryId;
              }
            });

            // 合并数据（排除重复项）
            const mergedCategories = [...existingCategories];
            const mergedUrls = [...existingUrls];

            // 按批次处理分类，避免一次处理太多数据
            const categoriesToAdd = [];
            for (const newCat of chromeBookmarks.categories) {
              if (!existingCategories.some(c => c.name === newCat.name)) {
                categoriesToAdd.push(newCat);
              }
            }

            // 按批次处理URL，避免一次处理太多数据
            const urlsToAdd = [];
            for (const newUrl of chromeBookmarks.urls) {
              if (!existingUrls.some(u => u.url === newUrl.url)) {
                urlsToAdd.push(newUrl);
              }
            }

            mergedCategories.push(...categoriesToAdd);
            mergedUrls.push(...urlsToAdd);

            console.log('Merged data - categories:', mergedCategories.length, 'URLs:', mergedUrls.length);

            // 保存合并后的数据
            try {
              // 先保存分类
              await storage.set({
                [CATEGORIES_STORE]: mergedCategories
              });

              // 再保存URL
              await storage.set({
                [URLS_STORE]: mergedUrls
              });

              console.log('Merged data saved successfully');

              resolve({
                categories: mergedCategories,
                urls: mergedUrls,
                imported: {
                  categories: categoriesToAdd.length,
                  urls: urlsToAdd.length
                }
              });
            } catch (saveError) {
              console.error('Error saving merged data:', saveError);
              reject(saveError);
            }
          } catch (error) {
            console.error('Error in merge process:', error);
            reject(error);
          }
        });
      });
    } else {
      // 覆盖模式：直接替换现有数据
      console.log('Replace mode - saving categories:', chromeBookmarks.categories.length);

      try {
        // 先保存分类
        await storage.set({
          [CATEGORIES_STORE]: chromeBookmarks.categories
        });

        console.log('Categories saved, now saving URLs:', chromeBookmarks.urls.length);

        // 再保存URL
        await storage.set({
          [URLS_STORE]: chromeBookmarks.urls
        });

        console.log('All data saved successfully in replace mode');

        return {
          categories: chromeBookmarks.categories,
          urls: chromeBookmarks.urls,
          imported: {
            categories: chromeBookmarks.categories.length,
            urls: chromeBookmarks.urls.length
          }
        };
      } catch (saveError) {
        console.error('Error saving data in replace mode:', saveError);
        throw saveError;
      }
    }
  } catch (error) {
    console.error('导入书签失败:', error);
    throw error;
  }
};

/**
 * 从JSON文件导入书签数据
 * @param {string|Object} jsonData - JSON字符串或对象
 * @param {Boolean} merge - 是否合并现有数据，默认为false（覆盖）
 * @returns {Promise<Object>} 导入结果
 */
export const importFromJson = async (jsonData, merge = false) => {
  try {
    console.log('Starting JSON import, merge mode:', merge);

    // 解析JSON数据
    let bookmarkData;
    if (typeof jsonData === 'string') {
      try {
        bookmarkData = JSON.parse(jsonData);
      } catch (parseError) {
        console.error('JSON解析错误:', parseError);
        throw new Error('无效的JSON格式');
      }
    } else if (typeof jsonData === 'object') {
      bookmarkData = jsonData;
    } else {
      throw new Error('无效的数据类型');
    }

    // 验证导入数据格式
    if (!bookmarkData || !bookmarkData.categories || !bookmarkData.urls) {
      console.error('无效的书签数据结构:', bookmarkData);
      throw new Error('导入数据缺少必要的字段（categories和urls）');
    }

    console.log('Parsed JSON data:', bookmarkData);

    // 验证每个书签和分类
    const validatedData = {
      categories: [],
      urls: []
    };

    // 验证分类数据
    for (const category of bookmarkData.categories) {
      const validCategory = validateBookmarkData(category);
      if (validCategory) {
        validatedData.categories.push(validCategory);
      }
    }

    // 验证URL数据
    for (const url of bookmarkData.urls) {
      const validUrl = validateBookmarkData(url);
      if (validUrl && validUrl.url) {
        validatedData.urls.push(validUrl);
      }
    }

    console.log('Validated data - categories:', validatedData.categories.length, 'URLs:', validatedData.urls.length);

    // 使用与Chrome书签导入相同的逻辑处理数据
    if (merge) {
      return new Promise((resolve, reject) => {
        storage.get([CATEGORIES_STORE, URLS_STORE], async (result) => {
          try {
            console.log('Existing data for merge:', result);
            const existingCategories = result[CATEGORIES_STORE] || [];
            const existingUrls = result[URLS_STORE] || [];

            // 合并数据（排除重复项）
            const mergedCategories = [...existingCategories];
            const mergedUrls = [...existingUrls];

            // 按批次处理分类，避免一次处理太多数据
            const categoriesToAdd = [];
            for (const newCat of validatedData.categories) {
              if (!existingCategories.some(c => c.id === newCat.id)) {
                categoriesToAdd.push(newCat);
              }
            }

            // 按批次处理URL，避免一次处理太多数据
            const urlsToAdd = [];
            for (const newUrl of validatedData.urls) {
              if (!existingUrls.some(u => u.url === newUrl.url)) {
                urlsToAdd.push(newUrl);
              }
            }

            mergedCategories.push(...categoriesToAdd);
            mergedUrls.push(...urlsToAdd);

            console.log('Merged data - categories:', mergedCategories.length, 'URLs:', mergedUrls.length);

            // 保存合并后的数据
            try {
              // 先保存分类
              await storage.set({
                [CATEGORIES_STORE]: mergedCategories
              });

              // 再保存URL
              await storage.set({
                [URLS_STORE]: mergedUrls
              });

              console.log('Merged data saved successfully');

              resolve({
                categories: mergedCategories,
                urls: mergedUrls,
                imported: {
                  categories: categoriesToAdd.length,
                  urls: urlsToAdd.length
                }
              });
            } catch (saveError) {
              console.error('Error saving merged data:', saveError);
              reject(saveError);
            }
          } catch (error) {
            console.error('Error in merge process:', error);
            reject(error);
          }
        });
      });
    } else {
      // 覆盖模式：直接替换现有数据
      console.log('Replace mode - saving categories:', validatedData.categories.length);

      try {
        // 先保存分类
        await storage.set({
          [CATEGORIES_STORE]: validatedData.categories
        });

        console.log('Categories saved, now saving URLs:', validatedData.urls.length);

        // 再保存URL
        await storage.set({
          [URLS_STORE]: validatedData.urls
        });

        console.log('All data saved successfully in replace mode');

        return {
          categories: validatedData.categories,
          urls: validatedData.urls,
          imported: {
            categories: validatedData.categories.length,
            urls: validatedData.urls.length
          }
        };
      } catch (saveError) {
        console.error('Error saving data in replace mode:', saveError);
        throw saveError;
      }
    }
  } catch (error) {
    console.error('导入JSON书签失败:', error);
    throw error;
  }
}; 